package com.net.xpay.web.secutiry;

import com.net.common.enums.EnumUtil;
import com.net.common.util.NetUtil;
import com.net.xpay.common.enums.user.ClientFrom;
import com.net.xpay.common.enums.user.LoginMethod;
import com.net.xpay.core.constant.WebConstant;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
  on 01/02/2018.
 */
public class FormLoginFilter extends AbstractAuthenticationProcessingFilter {

    public FormLoginFilter() {
        super(WebConstant.LOGIN_URL);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        FormLoginToken token = new FormLoginToken();
        token.setMobile(request.getParameter("mobile"));
        token.setLoginMethod(EnumUtil.getStringEnum(request.getParameter("loginMethod"), LoginMethod.class));
        token.setPassword(request.getParameter("password"));
        token.setCheckCode(request.getParameter("checkCode"));
        token.setCaptcha(request.getParameter("captcha"));
        token.setClientFrom(EnumUtil.getStringEnum(request.getParameter("clientFrom"), ClientFrom.class));
        token.setRememberMe(Boolean.valueOf(request.getParameter("rememberMe")));

        token.setTime(LocalDateTime.now());
        token.setIp(NetUtil.getRequestRealIp(request));

        return getAuthenticationManager().authenticate(token);
    }

}
